package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.ObjectUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalAdapterImpl extends TypeAdapter<BigDecimal> {


	@Override
	public void write(JsonWriter out, BigDecimal value) throws IOException {
		if(ObjectUtils.isEmpty(value)){
			out.value("");
			return;
		}
		DecimalFormat decimalFormat = new DecimalFormat("###################.###########");		
		out.value(decimalFormat.format(value));
	}

	@Override
	public BigDecimal read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			in.nextNull();
			return new BigDecimal("0");
		}
		String str = in.nextString();
		if (ObjectUtils.isNotEmpty(str)) {
			str = str.replace("\"", "");
			if (ObjectUtils.isEmpty(str)) {
				return new BigDecimal("0");
			} else {
				return new BigDecimal(str);
			}
		} else {
			return new BigDecimal("0");
		}
	}

}
